from abc import ABC, abstractmethod
from collections import namedtuple

Customer = namedtuple("Customer", "name fidelity")


# 定义商品 --型号，数量，单价
class LineItem:
    def __init__(self, product, quantity, price):
        self.product = product
        self.quantity = quantity
        self.price = price

    def total(self):
        return self.price * self.quantity


# 定义订单 --客户名称，购物车，促销方式
class Order:
    def __init__(self, customer, cart, promotion=None):
        self.customer = customer
        self.cart = list(cart)
        self.promotion = promotion

    def total(self):
        if not hasattr(self, "__total"):  # hasattr是什么？
            self.__total = sum(item.total()
                               for item in self.cart)  # sum直接加总循环出来的元素？
        return self.__total

    def due(self):
        if self.promotion is None:
            discount = 0
        else:
            discount = self.promotion(self)  # promotion类下定义了discount方法
        return self.total() - discount

    def __repr__(self) -> str:
        fmt = "<Order total: {:.2f} due: {:.2f}>"
        return fmt.format(self.total(), self.due())


# 下面开始时具体的折扣策略
def fidelity_promo(order):
    """为积分1000以上的顾客提供5%折扣"""
    return order.total() * 0.05 if order.customer.fidelity >= 1000 else 0


def bulk_item_promo(order):
    """单个商品为20个以上的提供10%折扣"""
    discount = 0
    for item in order.cart:
        if item.quantity >= 20:
            discount += item.total() * 0.1
    return discount


def large_order_promo(order):
    """订单中的不同商品达到10个以上时提供7%折扣"""
    distinct_items = {item.product for item in order.cart}
    if len(distinct_items) >= 10:
        return order.total() * 0.07
    return 0


promos = [
    globals()[name] for name in globals()
    if name.endswith("_promo") and name != "best_promo"
]


def best_promo(order):
    """选择可用的最佳折扣
    """
    return max(promo(order) for promo in promos)


def doctest():
    joe = Customer("John Doe", 0)
    ann = Customer("Ann Smith", 1100)
    cart = [
        LineItem("banana", 4, 0.5),
        LineItem("apple", 10, 1.5),
        LineItem("watermellon", 5, 5.0),
    ]
    return Order(joe, cart, best_promo)


if __name__ == "__main__":
    new = doctest()
    print(new)
    t = [1, 2, 3]
    print(t)
    T = list(t)
    print(T)
    print(globals())